<script setup lang="ts">
import { reactive, ref } from "vue";
import type { FormInstance, FormRules } from "element-plus";
import { ApiUser } from "../../api/index.ts";
import { useRouter } from "vue-router";
import { useDashboardStore } from "../../store/index.ts";
import { User, View } from "@element-plus/icons-vue";

const data = reactive({
  user_name: "",
  user_pwd: "",
});

const dashboardStore = useDashboardStore();
const formRef = ref<FormInstance>();
const rules: FormRules = {
  user_name: [
    { required: true, message: "请输入用户名", trigger: "blur" },
    { min: 2, max: 20, message: "用户名长度在2-20个字符", trigger: "blur" },
  ],
  user_pwd: [
    { required: true, message: "请输入密码", trigger: "blur" },
    { min: 2, max: 20, message: "密码长度在2-20个字符", trigger: "blur" },
  ],
};
const router = useRouter();

const login = async () => {
  // await formRef.value?.validate();
  // const token = await ApiUser.login(data);
  // sessionStorage.setItem("token", token);
  // const { init } = useDashboardStore();
  // await init();
  // router.replace("/");
     await formRef.value?.validate()           //触发表单验证
    const token = await ApiUser.login(data)  //通过了发ajax
    sessionStorage.setItem('token', token)    // 把token存起来
    await dashboardStore.init()
    await router.replace('/')  
};
</script>

<template>
  <div class="login">
    <el-card>
      <h1 slot="header">教育云平台</h1>
      <el-form
        label-width="80px"
        :model="data"
        :rules="rules"
        status-icon
        ref="formRef"
      >
        <el-form-item label="账户名称:" prop="user_name" label-width="100px" class="name"
          ><el-input v-model="data.user_name" ><template #prefix><el-icon><User/> </el-icon></template></el-input>
        </el-form-item>
        <el-form-item label="密码:" prop="user_pwd" label-width="100px" class="pwd" @keyup.enter="login"
          ><el-input v-model="data.user_pwd" show-password>
            <template #prefix><el-icon><View/> </el-icon></template>
            </el-input
        ></el-form-item>
        <el-form-item>
          <el-button
            @click="login"
            plain="true"
            type="primary"
            size="large"
            round
            class="btn"
            >登录</el-button
          >
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<style scoped lang="scss">
.login {
  width: 100%;
  height: 100%;
  background-color: #87CEFA;
  .el-card {
    position: absolute;
    top: 50%;
    left: 50%;
    transform: translate(-50%, -50%);
    width: 500px;
    background-color: #F5F5DC;
    h1 {
      text-align: center;
      font-size: 30px;
      margin-bottom: 15px;
      color: #8B4513;
    }
    .el-form{
      .name{
        color: #00BFFF;
      }
      .btn{
        color: #00BFFF;
        margin: 10px 0 0 110px;
        &:hover{
          background-color: #8bb9c9;
        }
      }
    }
  }
}
</style>
